#include "fun.h"
#include "ds1302.h"  
#include "onewire.h"

u8 bdata LED;
u8 t_200ms = 0,L1_flag = 0;
u16 temperature = 0;
sbit L1 = LED^0;
sbit L2 = LED^1;
sbit L3 = LED^2;
u8 code t_display[]={                       //????
//   0    1    2    3    4    5    6    7    8    9    
    0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,
    0xBF,0x86,0xDB,0xCF,0xE6,0xED,0xFD,0x87,0xFF,0xEF,
		0x40,0x00,0x3E};    // - black U
u8 code T_COM[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};      //??

u8 disp_data[][8]=
{
	{22,1,21,21,21,0,0,0},
	{22,2,21,0,0,20,0,0},
	{22,3,21,21,21,21,0,0}
};

void Timer2Init(void)		//1毫秒@12.000MHz
{
	AUXR |= 0x04;		//定时器时钟1T模式
	T2L = 0x20;		//设置定时初值
	T2H = 0xD1;		//设置定时初值
	AUXR |= 0x10;		//定时器2开始计时
	IE2 |= 0x04;
	EA = 1;
}

void main()
{
	buzzer(0);
	relay(0);
	L2 = 1;
	led(LED);
	temperature = read_tem();
	set_clock(23,59,50);
	Timer2Init();
	
	while(1)
	{
		EA = 0;
		get_time();
		EA = 1;	
		
		if(t_200ms)
		{
			t_200ms = 0;
			temperature = read_tem();
		}
		
		if(disp_flag == 1)
		{
			if(m_s)
			{
				disp_data[1][3] = m / 16;
				disp_data[1][4] = m % 16;
				disp_data[1][6] = s / 16;
				disp_data[1][7] = s % 16;
			}
			else
			{
				disp_data[1][3] = h / 16;
				disp_data[1][4] = h % 16;
				disp_data[1][6] = m / 16;
				disp_data[1][7] = m % 16;
			}
		}
		else if(disp_flag == 2)
		{
			disp_data[2][6] = param / 10;
			disp_data[2][7] = param % 10;
		}
		else if(disp_flag == 0)
		{
			disp_data[0][5] = temperature / 100;
			disp_data[0][6] = (temperature % 100) / 10 + 10;
			disp_data[0][7] = temperature % 10;
		}
	}
}

void t2_callback(void) interrupt 12
{
	static u8 i,t;
	static u8 L3_t;
	static u16 L1_t;
	t++;
	
	if(!(t%20))
		key_scan();
	if(t >= 200)
	{
		t = 0;
		t_200ms = 1;
	}
	
	if((temperature > (param * 10)) && !c_flag)
		relay_flag = 1;
	else if(!c_flag)
		relay_flag = 0;
	else if((s == 5) && c_flag && (relay_flag == 1))
		relay_flag = 0;
		
	if(s == 0 && m == 0)
	{
		L1_flag = 1;
		L1 = 1;
		if(c_flag)
			relay_flag = 1;
	}
	
	if(L1_flag)
	{
		L1_t++;
		if(L1_t >= 5000)
		{
			L1_t = 0;
			L1 = 0;
			L1_flag = 0;
		}
	}
	
	L2 = ~c_flag;
	
	if(relay_flag)
	{
		L3_t++;
		if(L3_t >= 100)
		{
			L3_t = 0;
			L3 = ~L3;
		}
	}
	else
	{
		L3 = 0;
		L3_t = 0;
	}
	
	led(LED);
	relay(relay_flag);

	i++;
	i %= 8;
	smg_disp(t_display[disp_data[disp_flag][i]],T_COM[i]);
}

